package display.renderer;

import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.util.Iterator;

import prefuse.Constants;
import prefuse.data.util.TreeNodeIterator;
import prefuse.render.AbstractShapeRenderer;
import prefuse.render.EdgeRenderer;
import prefuse.util.ColorLib;
import prefuse.visual.EdgeItem;
import prefuse.visual.NodeItem;
import prefuse.visual.VisualItem;
import weeny.pre.util.Geom;

public class BagTreeMapRenderer extends EdgeRenderer{
	static class NodeRenderer extends AbstractShapeRenderer {
	    private Rectangle2D m_bounds = new Rectangle2D.Double();
	    public NodeRenderer() {
	        m_manageBounds = false;
	    }
	    protected Shape getRawShape(VisualItem item) {
	    	m_bounds.setFrame(item.getBounds());
	        return m_bounds;
	    }
	}
	NodeRenderer ren = new NodeRenderer();
	private RoundRectangle2D rr = new RoundRectangle2D.Double();
	public BagTreeMapRenderer() {
		super(Constants.EDGE_TYPE_LINE, Constants.EDGE_ARROW_NONE);
	}
	@Override
	public void render(Graphics2D g, VisualItem item) {
		EdgeItem edge = (EdgeItem) item;
		if (edge.get("TREES") == null) {
			super.render(g, item);
			return;
		}
		if (item.get("TREES")!=null) {
			rr.setRoundRect(-item.getSize()/2, 0, item.getSize(), Geom.length(edge), 8, 8);
			m_arrowTrans.setToTranslation(edge.getSourceItem().getX(), edge.getSourceItem().getY());
	        m_arrowTrans.rotate(-HALF_PI + Math.atan2(Geom.deltaY(edge), Geom.deltaX(edge)));
	        Shape sr = m_arrowTrans.createTransformedShape(rr);
	        g.setPaint(ColorLib.getColor(item.getFillColor()));
            g.fill(sr);
            
			if (edge.getSourceItem().getX()>1200) {
				return;
			}

			NodeItem node = (NodeItem) item.get("TREES");
			Iterator<NodeItem> iter = new TreeNodeIterator(node);
			while(iter.hasNext()){
				NodeItem n = iter.next();
				Rectangle2D s = (Rectangle2D) ren.getRawShape(n);
				rr.setRoundRect(
						s.getX()-item.getSize()/2, s.getY(), s.getWidth(), s.getHeight(),
						8,8);
				Shape path = m_arrowTrans.createTransformedShape(rr);
				g.setPaint(ColorLib.getColor(n.getFillColor()));
	            g.fill(path);
	            g.setPaint(ColorLib.getColor(n.getStrokeColor()));
	            g.draw(path);
			}
		}
		
	}
}
